

#include "unity.h"
#include "unity_fixture.h"

#include "BSP_Sleep.h"

#include "ISO7816/i7816_activate.h"
#include "ISO7816/i7816_log.h"
#include "ISO7816/i7816.h"


// extern i7816_ifd_t i7816_ifd;
void i7816_hal_delay(uint32_t clk);
void i7816_hal_delay_ms(uint32_t ms);
uint32_t i7816_hal_get_clk_count(void);


TEST_GROUP(I7816);


TEST_SETUP(I7816)
{
	
}

TEST_TEAR_DOWN(I7816)
{
	
}


TEST(I7816, power_on)
{
	i7816_status_t status;
	i7816_init();
	
	for(int i = 0; i < 1000; i++){
		uint32_t c1 = i7816_hal_get_clk_count();
		LOG2_INF("c1: %lu", c1);
		i7816_hal_delay_ms(2);
		uint32_t c2 = i7816_hal_get_clk_count();
		LOG2_INF("c2: %lu", c2);
		uint32_t d = (uint32_t)(c2 - c1);
		LOG2_INF("c1: %lu, c2: %lu, c2-c1: %lu", c1, c2, d);
	}
	
	for( int i = 0; i < 1000; i++){

		// status = i7816_activate(&i7816_ifd);
		// if(!status){
		// 	break;
		// }
		LOG2_CONTROL(LOG2_CTRL_RESET);
		status = I7816_S_CARD_ABSENT;
		i7816_icc_state_t state = i7816_check_state(0);
		if(state & ICC_ST_PRESENT){
			status = i7816_power_on(0);
		}

		if(status == I7816_S_OK){
			uint8_t atr[32];
			uint8_t alen = 0;
			status = i7816_get_atr(0, atr, &alen);
			if(status == I7816_S_OK){
				I7816_LOG_BUF("atr", atr, alen);
			}
		}
		if(status == I7816_S_OK){
			//get version
			uint8_t capdu[] = {0x80, 0x60, 0x00, 0x00, 0x00};
			uint8_t rapdu[128] = {0};
			uint16_t rlen = 0;
			status = i7816_exchange_apdu(0, capdu, sizeof(capdu), rapdu, &rlen);
			if(status == I7816_S_OK){
				I7816_LOG_BUF("rapdu", rapdu, rlen);
			}
			else{
				I7816_LOG_ERR("exchange apdu fail: %d", status);
				i7816_power_off(0);
			}
		}
		if(status == I7816_S_OK){
			i7816_power_off(0);
		}

		BSP_Sleep_Ms(1000);
	}
	TEST_ASSERT_EQUAL_INT_MESSAGE(0, status, "PowerOn fail!");
	// if(!status){
	// 	I7816_LOG_BUF("atr", i7816_ifd.icc.atr, i7816_ifd.icc.alen);
	// }
}




